package com.esun.cheetah.view.personal;

import java.text.Format;
import java.text.SimpleDateFormat;

import android.app.Activity;
import android.app.ActivityGroup;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.esun.cheetah.R;

import com.esun.cheetah.biz.personal.personalcommunicater.PersonalLoginCommunicater;
import com.esun.cheetah.biz.personal.personalinfo.UserInfo;
import com.esun.cheetah.config.Config;
import com.esun.cheetah.config.Key;
import com.esun.cheetah.config.Language;
import com.esun.cheetah.view.HomeAct;
import com.esun.cheetah.view.personal.webview.WebviewActivity;
import com.esun.cheetah.view.setting.ValuesManager;
import com.esun.cheetah.view.setting.com.SetCommu;
import com.esun.util.EditTextInputUitl;
import com.esun.util.VersionUtils;
import com.esun.util.ViewerUtil;
import com.esun.util.log.EDebug;
import com.esun.util.md5.MD5;

/**
 * 
 * @Package com.esun.cheetah.view.personal.LoginAct
 * @ClassName: LoginAct
 * @Description: TODO(user login interface)
 * @author hxt <br/>
 * @date create at 2012-3-29 下午8:02:10
 * 
 */

public class LoginAct extends ActivityGroup implements OnClickListener,
		TextView.OnEditorActionListener {
	/** Called when the activity is first created. */
	private Button btnLogin; // 登錄按鈕
	private Button btnRegist; // 注册..
	private Button btnCleanUserName; // 清空用户名..
	private Button btnCleanUserPass; // 清空密码..

	private EditText edtUserName; // 输入用户名
	private EditText edtUserPass; // 输入密码

	private Handler handler;
	/** 时间日期装换 */
	public static Format format = new SimpleDateFormat("yyyyMMdd");
	/** 设置值的管理类 */
	private ValuesManager valuesManager;
	private String strUserName;// 输入的用户名
	private String strUserPass;// 输入的密码
	private String strUserPassMD5;// 转为md5
	private ProgressDialog loginDialog;
	private long loginTime;// 登陆时间
	private String shareUserName;// 保存的用户名
	private String shareUserpass;// 保存的密码
	private SharedPreferences sharedPreferences;
	private PersonalLoginCommunicater personallogincommunicater;
	private ProgressDialog progressDialog;
	// private MatchListSwitcher matchListSwitcher;
	/** 设置值的handler */
	Handler setHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case Config.COMMUNICATER_SUCCESS:
				break;
			}
		}
	};
	/** 验证是否在线 */
	Handler isOnlineHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case Config.COMMUNICATER_SUCCESS:
				break;
			}
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		readSharedPreferences();
		setContentView(R.layout.login);
		uiInit();
		initHandler();
		loginDialog = new ProgressDialog(getParent());
		progressDialog = ViewerUtil.showProgressDialog(getParent(),
				Language.MSG_LOADING);
		if (null == shareUserName && null == shareUserpass) {
			// setContentView(R.layout.login);
			// uiInit();
			// initHandler();
			EDebug.o("loginAct");
		} else {

			// initHandler();
			progressDialog.show();
			saveUsedSharedPreferences();
			// setContentView(R.layout.loggedin);
			startcommunicatlogin(handler, shareUserName, shareUserpass, this);
		}
	}

	private void readSharedPreferences() {
		sharedPreferences = getSharedPreferences(Key.SHAREDPREFERENCES_NAME,
				Context.MODE_PRIVATE);
		shareUserName = sharedPreferences.getString(Key.KEY_USERNAME, null);
		shareUserpass = sharedPreferences.getString(Key.SAVE_PASSWORD, null);// getString()第二个参数为缺省值，如果preference中不存在该key，将返回缺省值
		EDebug.o("name  ------  " + shareUserName);
		EDebug.o("pass  ------" + shareUserpass);
	}

	private void uiInit() {
		valuesManager = new ValuesManager(this);
		btnLogin = (Button) findViewById(R.id.loginact_btn_login);
		btnLogin.setOnClickListener(this);

		btnRegist = (Button) findViewById(R.id.loginact_btn_regist);
		btnRegist.setOnClickListener(this);

		edtUserName = (EditText) findViewById(R.id.loginact_edt_userName);
		btnCleanUserName = (Button) findViewById(R.id.loginact_btn_claenUserNmae);
		edtUserName = new EditTextInputUitl(edtUserName, btnCleanUserName)
				.getEditText();
		// edtUserName.setText(strUserName);

		edtUserPass = (EditText) findViewById(R.id.loginact_edt_userPass);
		btnCleanUserPass = (Button) findViewById(R.id.loginact_btn_claenUserPass);
		edtUserPass = new EditTextInputUitl(edtUserPass, btnCleanUserPass)
				.getEditText();
		// edtUserPass.setText(strUserPass);
	}

	private void initHandler() {

		handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				switch (msg.what) {
				case Config.COMMUNICATER_SUCCESS:
					if (null == shareUserName && null == shareUserpass) {
						saveSharedPreferences();
					} else {
						saveUsedSharedPreferences();

					}

					saveUserInfo();
					gotoLoggedinAct();

					// MatchListManager.getInstance().setLoggedIn(true);

					if (progressDialog.isShowing()) {
						progressDialog.cancel();
					}
					closeDialog();
					break;
				case Config.COMMUNICATER_FAIL:
					// ViewerUtil.showTipDialog(getParent(),
					// personallogincommunicater.getServerMsg(), false);
					if (msg.obj != null && ((String) msg.obj).equals("3")) {
						showUnlockDialog(personallogincommunicater
								.getServerMsg());
					} else if (msg.obj != null
							&& ((String) msg.obj).equals("15")) {
						ViewerUtil.showTipDialog(getParent(),
								"此ip多次登录失败,将被锁定三小时", false);
					} else {
						Toast.makeText(getParent(),
								personallogincommunicater.getServerMsg(), 500)
								.show();
					}

					if (progressDialog.isShowing()) {
						progressDialog.cancel();
					}

					closeDialog();
					// setContentView(R.layout.login);
					//
					// uiInit();
					// edtUserName.setText(UserInfo.getUserInfo().getUsernameString());
					// edtUserPass.setText(UserInfo.getUserInfo().getUserpassword());
					break;
				case Config.COMMUNICATER_EXCEPTION:
					// ViewerUtil.showTipDialog(getParent(),
					// Language.NERWORK_ABORT, false);

					Toast.makeText(getParent(), Language.NERWORK_ABORT, 500)
							.show();
					if (progressDialog.isShowing()) {
						progressDialog.cancel();
					}

					EDebug.o("通讯异常" + UserInfo.getUserInfo().getFreezemoney());
					closeDialog();
					// setContentView(R.layout.login);
					// uiInit();
					// edtUserName.setText(UserInfo.getUserInfo().getUsernameString());
					// edtUserPass.setText(UserInfo.getUserInfo().getUserpassword());
					break;
				}
			}
		};
	}

	protected void saveUsedSharedPreferences() {
		sharedPreferences = getSharedPreferences(Key.SHAREDPREFERENCES_NAME,
				Context.MODE_PRIVATE);
		Editor editor = sharedPreferences.edit();
		editor.putString(Key.KEY_USERNAME, shareUserName);
		editor.putString(Key.SAVE_PASSWORD, shareUserpass);
		editor.commit();
		EDebug.o("save strUserName2--" + shareUserName);
		EDebug.o("save strUserPassMD52--" + shareUserpass);
	}

	private void closeDialog() {
		if (loginDialog.isShowing()) {
			loginDialog.cancel();
		} else {
			EDebug.o("nodialog");
		}
	}

	private void saveUserInfo() {
		loginTime = System.currentTimeMillis();
		UserInfo.getUserInfo().setLogintime(loginTime);
		EDebug.o("logintime------" + loginTime);
	}

	public void onClick(View v) {
		try {
			switch (v.getId()) {
			case R.id.loginact_btn_login:
				// 验证输入限制条件
				if (!edtUserName.getText().equals(null)
						&& edtUserName.getText().toString().length() < Language.NUM_ONE) {
					EDebug.o("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
					// ViewerUtil.showTipDialog(getParent(),
					// Language.ENTER_USERNAME, false);
					Toast.makeText(getParent(), Language.ENTER_USERNAME, 500)
							.show();
				} else if (!edtUserPass.getText().equals(null)
						&& edtUserPass.getText().toString().length() < Language.NUM_ONE) {
					// ViewerUtil.showTipDialog(getParent(),
					// Language.ENTER_LOGIN_PASSWORD, false);
					Toast.makeText(getParent(), Language.ENTER_LOGIN_PASSWORD,
							500).show();
				} else if (edtUserName.getText().toString().length() < Language.NUM_FOUR
						|| edtUserName.getText().toString().length() > Language.NUM_SIXTEEN) {
					// ViewerUtil.showTipDialog(getParent(),
					// Language.ENTER_RIGHT_USERNAME, false);
					Toast.makeText(getParent(), Language.ENTER_RIGHT_USERNAME,
							500).show();
				} else if (edtUserPass.getText().toString().length() < Language.NUM_SIX
						|| edtUserPass.getText().toString().length() > Language.NUM_FIVETEEN) {
					// ViewerUtil.showTipDialog(getParent(),
					// Language.ENTER_RIGHT_PASSWORD, false);
					Toast.makeText(getParent(), Language.ENTER_RIGHT_PASSWORD,
							500).show();
				} else {
					getInputInfo();
					startcommunicatlogin(handler, strUserName, strUserPassMD5,
							this);
					showloginDialog();

				}
				break;
			case R.id.loginact_btn_regist:
				gotoRegistAct();
				break;
			case R.id.loginact_btn_claenUserNmae:
				edtUserName.setText(Config.NULLMARK);
				break;

			case R.id.loginact_btn_claenUserPass:
				edtUserPass.setText(Config.NULLMARK);
				break;
			default:
				break;
			}
		} catch (Exception e) {
		}
	}

	private void gotoLoggedinAct() {
		Intent intent = new Intent();
		intent.setClass(LoginAct.this, HomeAct.class);
		PersonalAct.flag = Language.FLAG_SIX;
		HomeAct.flag = Language.FLAG_FOUR;
		startActivity(intent);
		LoginAct.this.finish();
	}

	private void saveSharedPreferences() {
		sharedPreferences = getSharedPreferences(Key.SHAREDPREFERENCES_NAME,
				Context.MODE_PRIVATE);
		Editor editor = sharedPreferences.edit();
		editor.putString(Key.KEY_USERNAME, strUserName);
		editor.putString(Key.SAVE_PASSWORD, strUserPassMD5);
		editor.commit();
		EDebug.o("save strUserName--" + strUserName);
		EDebug.o("save strUserPassMD5--" + strUserPassMD5);
	}

	private void gotoRegistAct() {
		Intent registIntent = new Intent();
		registIntent.setClass(LoginAct.this, RegistAct.class);
		startActivity(registIntent);
		LoginAct.this.finish();
	}

	private void showloginDialog() {
		loginDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		loginDialog.setMessage(Language.LOGGING);
		loginDialog.setIndeterminate(false);// 设置进度条是否为不明确
		loginDialog.setCancelable(true);// 设置进度条是否可以按退回键取消
		loginDialog.show();
	}

	private void startcommunicatlogin(Handler handler, String username,
			String userpass, Context context) {

		personallogincommunicater = new PersonalLoginCommunicater(handler,
				username, userpass, context);
		personallogincommunicater.startCommunicate();
		new SetCommu(setHandler, this, valuesManager.getBeginTime(),
				valuesManager.getEndTime()).startCommunicate();
		UserInfo.getUserInfo().setAccountProct(true);
		// openNotice();
	}

	private void getInputInfo() {
		strUserName = edtUserName.getText().toString();
		strUserPass = edtUserPass.getText().toString();

		UserInfo.getUserInfo().setUsernameString(strUserName);
		UserInfo.getUserInfo().setUserpassword(strUserPass);
		strUserPassMD5 = MD5.md5(strUserPass);
		EDebug.o("strUserName---------------" + strUserName);
		EDebug.o("strUserPass---------------" + strUserPass);
		EDebug.o("handler---------------" + handler);
	}

	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
		return true;
	}



	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			Activity parent = getParent();
			if (parent != null) {
				parent.onKeyDown(keyCode, event);
				return true;
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	// 解锁提示框
	private void showUnlockDialog(String tip) {

		SharedPreferences sharedPrefValues = getSharedPreferences(
				Config.SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE);
		final String imei = sharedPrefValues.getString(Config.IMEI, "");

		final Dialog unlockDialog = new Dialog(getParent(), R.style.dialog);
		unlockDialog.getWindow().setContentView(
				R.layout.viewerutil_dialog_showlogout);

		TextView tvMsg = (TextView) unlockDialog.getWindow().findViewById(
				R.id.show);
		tvMsg.setText(tip);

		Button btnOk = (Button) unlockDialog.getWindow()
				.findViewById(R.id.sure);
		btnOk.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				unlockDialog.dismiss();
			}
		});

		Button btnUnlock = (Button) unlockDialog.getWindow().findViewById(
				R.id.cancel);

		EDebug.o("--------------------------------------------------------->>>"
				+ Config.URL_UNLOCK + "imei=" + imei + "serial="
				+ VersionUtils.getInstance().getSerial(LoginAct.this));
		btnUnlock.setText("解锁");
		btnUnlock.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				unlockDialog.dismiss();
				if (!imei.equals("")) {
					startActivity(new Intent()
							.setClass(LoginAct.this, WebviewActivity.class)
							.putExtra(
									"url",
									Config.URL_UNLOCK
											+ "imei="
											+ imei
											+ "&serial="
											+ VersionUtils.getInstance()
													.getSerial(LoginAct.this))
							.putExtra("title", "用户解锁"));
					LoginAct.this.finish();
				}
			}
		});

		unlockDialog.show();
	}

}
